package com.na.onlineservey

import org.springframework.transaction.annotation.Transactional
import com.docu.Service
import javax.sql.DataSource
import groovy.sql.Sql
import com.docu.common.Action
import com.na.onlineservey.Question

class QuestionService extends Service {
    static transactional = false
    DataSource dataSource
    Sql sql

    @Transactional
    public Integer create(Object object) {
        Map map = (Map) object
        Question questionInstance = map?.questionInstance
        List<QuestionAnsweringOption> questionAnsweringOptionList = map?.questionAnsweringOptionList
        Question question = questionInstance.save(false)
        questionAnsweringOptionList.each {
            it.question = question
            it.save(true)
        }
        return new Integer(1)
    }

    @Transactional
    public Integer update(Object object) {
        Question questionInstance = (Question) object
        if (questionInstance.save()) {
            return new Integer(1)
        }
        else {
            return new Integer(0)
        }
    }

    @Transactional
    public Integer delete(Object object) {
        Question questionInstance = (Question) object
        questionInstance.delete()
        return new Integer(1)
    }

    @Transactional(readOnly = true)
    public Map getListForGrid(Action action) {
        List<Question> objList = Question.withCriteria {
            if (action.resultPerPage != -1) {
                maxResults(action.resultPerPage)
            }
            firstResult(action.start)
            order(action.sortCol, action.sortOrder)
        }
        long total = Question.count()
        return [objList: objList, count: total]
    }

    @Transactional(readOnly = true)
    public List<Question> list() {
        return Question.list()
    }

    @Transactional(readOnly = true)
    public Question read(Long id) {
        return Question.read(id)
    }

    @Transactional(readOnly = true)
    public Question search(String fieldName, String fieldValue) {
        String query = "from Question as docu where docu." + fieldName + " = '" + fieldValue + "'"
        return Question.find(query)
    }
}
